package com.example.mvvmcoroutineexample.viewmodels

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.mvvmcoroutineexample.R
import com.example.mvvmcoroutineexample.models.AuthService
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch

class LoginViewModel : ViewModel() {
    private var currentUserName: String = ""
    private var currentPassword: String = ""

    private val _uiState: MutableStateFlow<UiState> = MutableStateFlow(UiState())
    val uiState: Flow<UiState> = _uiState

    private val _authMessage: MutableSharedFlow<Int> = MutableSharedFlow<Int>()
    val authMessage: Flow<Int> = _authMessage

    private val authService = AuthService()

    fun userNameEntered(userName: String) {
        currentUserName = userName
        checkButtonState()
    }

    fun passwordEntered(password: String) {
        currentPassword = password
        checkButtonState()
    }

    private fun checkButtonState() {
        _uiState.update {
            it.copy(isButtonEnabled = currentUserName.isNotBlank() && currentPassword.isNotBlank())
        }
    }

    fun login(userName: String, password: String) {
        viewModelScope.launch {
            _uiState.update {
                it.copy(isProgressVisible = true, isButtonEnabled = false)
            }
            val isAuthorized: Boolean = authService.auth(userName, password)
            _uiState.update {
                it.copy(isProgressVisible = false, isButtonEnabled = true)
            }
            if (isAuthorized) {
                _authMessage.emit(R.string.user_authorized)
            } else {
                _authMessage.emit(R.string.user_not_authorized)
            }
        }
    }
}